<template>
    <div class="p-2">
      <transition>
        <!-- 查询区 -->
        <div class="search" v-show="showSearch">
          <el-form
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="用户名" prop="name">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号" prop="name">
              <el-input
                v-model="queryParams.phoneNumber"
                placeholder="请输入手机号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in statusArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="会员状态" prop="memberStatus">
              <el-select
                v-model="queryParams.memberStatus"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in selectArr.memberStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="区域查询">
              <el-cascader
                :options="searchData.searchRegionTree"
                clearable
                :props="DialogData.treeProps"
                :show-all-levels="false"
                @change="handleRegionChange"
              >
                <template #default="{ node }">
                  <span>{{ node.label }}</span>
                </template>
              </el-cascader>
            </el-form-item>

            <el-form-item label="机构查询" prop="organizationArr">
              <el-cascader
                clearable
                :props="DialogData.treeProps"
                :options="searchData.searchOrganizationTree"
                :show-all-levels="false"
                @change="handleOrganizationChange"
              >
                <template #default="{ node }">
                  <span>{{ node.label }}</span>
                </template>
              </el-cascader>
            </el-form-item> -->

            <el-form-item label="注册时间" prop="time">
              <!-- <el-input v-model="queryParams.time" placeholder="请输入注册时间" clearable @keyup.enter="handleQuery" /> -->
              <el-date-picker
                v-model="queryParams.time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">
                搜索
              </el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>

      <!-- 按钮区 -->
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb-1">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleCreate"
                v-hasPermi="['system:user:add']"
              >
                新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleEditUser()"
                v-hasPermi="['system:user:edit']"
              >
                编辑
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete()"
                v-hasPermi="['system:user:remove']"
              >
                删除
              </el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['system:user:import']"
              >
                导出
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-upload
                ref="upload"
                class="upload-demo"
                action="#"
                :limit="1"
                :on-change="beforeUpload"
                :on-exceed="handleExceed"
                :auto-upload="false"
              >
                <template #trigger>
                  <el-button
                    type="info"
                    plain
                    icon="Delete"
                    @click="handleImport"
                    v-hasPermi="['system:user:import']"
                  >
                    导入
                  </el-button>
                </template>
              </el-upload>
            </el-col>

            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="Download"
                v-hasPermi="['system:user:import']"
              >
                <a
                  href="https://fanzhiedu.oss-cn-chengdu.aliyuncs.com/template/%E5%AD%A6%E6%A0%A1%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx"
                >
                  下载导入模板
                </a>
              </el-button>
            </el-col>
            <right-toolbar
              v-model:showSearch="showSearch"
              @queryTable="getClientUserList"
            ></right-toolbar>
          </el-row>
        </template>

        <!-- 列表区 -->
        <el-table
          v-loading="loading"
          :data="clientUserList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column
            label="用户名"
            align="center"
            prop="userName"
            v-if="true"
          />

          <el-table-column label="状态" prop="status">
            <template #default="{ row }: { row: ClientUserVo }">
              <el-tag :type="UserStatusTypeMap.get(row.status ?? '') ?? 'info'">
                {{ row.statusMsg }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="昵称" align="center" prop="nickName" />
          <el-table-column label="手机号" align="center" prop="phoneNumber" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="FolderOpened"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <span v-hasPermi="['system:user:edit']" class="ml-10px">
                <el-tooltip content="编辑" placement="top" :enterable="false">
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleEditUser(scope.row)"
                  ></el-button>
                </el-tooltip>
              </span>
              <span v-hasPermi="['system:user:remove']" class="ml-10px">
                <el-tooltip content="删除" placement="top" :enterable="false">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getClientUserList"
        />
      </el-card>

      <!-- 弹出框 -->
      <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="60%"
        center
        :show-close="false"
        :close-on-click-modal="false"
      >
        <el-form
          :model="currentDialogData"
          ref="diologFormRef"
          :rules="rules"
          :inline="true"
          label-width="78px"
          class="dialogForm"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.userName"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>

          <el-form-item label="会员设置" prop="memberStatus">
            <el-select
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.memberStatus"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.memberStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="用户昵称" prop="nickName">
            <el-input
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.nickName"
              placeholder="请输入昵称"
              clearable
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.password"
              placeholder="请输入密码"
              clearable
            />
          </el-form-item>

          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.phoneNumber"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.email"
              placeholder="请输入邮箱"
              clearable
            />
          </el-form-item>

          <el-form-item label="性别" prop="sex">
            <el-select
              :disabled="dialogData.isDisabled"
              v-model="currentDialogData.sex"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in selectArr.sexArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="机构" prop="organizationArr">
            <el-cascader
              v-model="currentDialogData.organizationId"
              clearable
              :props="DialogData.treeProps"
              :options="searchData.searchOrganizationTree"
              :show-all-levels="false"
              @change="dialogOrganizationChange"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-cascader>
          </el-form-item> -->

          <el-form-item class="dialogFooter">
            <el-button type="primary" icon="Search" @click="addSubmit">
              提交
            </el-button>
            <el-button icon="Refresh" @click="handleCloseDialog">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>

  <script setup lang="ts">
  import {
    getClientUserList as getClientUserListApi,
    createClientUser as createClientUserApi,
    getClientUserDetail as getClientUserDetailApi,
    updateClientUser as updateClientUserApi,
    deleteClientUser as deleteClientUserApi,
    importExcel as importExcelApi,
  } from "@/service/api/system/frontUser";
  import { ElForm } from "element-plus";
  import { download } from "@/utils/request";
  import { ref } from "vue";
  import { genFileId } from "element-plus";
  import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
  import RightToolbar from "@/components/RightToolbar/index.vue";
  import Pagination from "@/components/Pagination/index.vue";
  import {
    ClientUserInfoVo,
    ClientUserVo,
  } from "@/service/api/system/frontUser/types.ts";
  import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
  import { to } from "await-to-js";
  import {
    UserStatusMap,
    UserStatusTypeMap,
  } from "@/maps/system/user/userStatusMap.ts";

  // uploadDOM实例对象
  const upload = ref<UploadInstance>();

  // 上传excel到后端
  const importExcel = async (formData: any) => {
    const res = await importExcelApi(formData);
    console.log(res);
  };

  // 选择文件后上传
  const beforeUpload = async (file: any) => {
    console.log(file);
    const formData = new FormData();
    formData.append("file", file.raw);
    await importExcel(formData);
  };

  // 选择文件超过一个时调用
  const handleExceed: UploadProps["onExceed"] = (files) => {
    upload.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    upload.value!.handleStart(file);
    console.log(file);
  };

  // 列表数据
  const clientUserList = ref<ClientUserVo[]>([]);

  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const queryFormRef = ref(ElForm);
  const diologFormRef = ref(ElForm);

  const dialog = reactive({
    visible: false,
    title: "",
  });

  // 获取用户列表BO
  const initGetUserList = {
    pageNum: 1,
    pageSize: 10,
    phoneNumber: "",
    status: "",
    userName: "",
    time: "",
    regionId: "",
    organizationId: "",
    memberStatus: "",
    orderByColumn: "createTime",
    orderType: "desc",
  };

  // 初始新增用户数据
  const initAddUserBO: ClientUserVo = {
    userName: "",
    email: "",
    nickName: "",
    status: "",
    phoneNumber: "",
    password: "",
    sex: "",
    id: "",
    memberStatus: "",
  };

  // 所有状态
  const statusArr = reactive([
    {
      value: "3",
      label: "未确认",
    },
    {
      value: "2",
      label: "禁言",
    },
    {
      value: "0",
      label: "正常",
    },
    {
      value: "1",
      label: "停用",
    },
  ]);

  // 参数，上方查询的数据
  const searchData = reactive({
    queryParams: {
      ...initGetUserList,
    },
    // 获取组织参数
    organizationParams: {
      pageSize: 10,
      pageNum: 1,
      name: "",
    },
    organizationArr: [],
    rules: {
      phoneNumber: [{ required: true, message: "手机不能为空", trigger: "blur" }],
      userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
      age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
      eMail: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
      memberStatus: [{ required: true, message: "会员状态不能为空", trigger: "blur" }],
      status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
    },
    searchRegionTree: [],
    searchOrganizationTree: [],
  });

  // dialog数据
  const dialogData = reactive({
    currentDialogData: {
      ...initAddUserBO,
    },
    isDisabled: false,
    treeProps: {
      checkStrictly: true,
      value: "id",
    },
  });

  // dialog的select
  const selectArr = reactive({
    statusArr: [
      {
        value: "3",
        label: "未确认",
      },
      {
        value: "2",
        label: "禁言",
      },
      {
        value: "0",
        label: "正常",
      },
      {
        value: "1",
        label: "停用",
      },
    ],
    sexArr: [
      {
        value: "0",
        label: "男",
      },
      {
        value: "1",
        label: "女",
      },
      {
        value: "2",
        label: "未知",
      },
    ],
    identityArr: [],
    memberStatus: [
      {
        value: "0",
        label: "非会员",
      },
      {
        value: "1",
        label: "普通会员",
      },
      {
        value: "2",
        label: "特殊会员",
      },
    ],
  });

  const { queryParams, rules } = toRefs(searchData);
  const { currentDialogData } = toRefs(dialogData);

  /**
   * 获得客户端用户列表
   */
  const getClientUserList = async (): Promise<boolean> => {
    loading.value = true;
    console.log(queryParams.value);
    const [err, res] = await to<BasePageResponse<ClientUserVo>, any>(
      getClientUserListApi(queryParams.value),
    );
    console.log(res);

    if (!err) {
      total.value = Number(res?.total ?? 0);
      clientUserList.value = res?.rows ?? [];
      clientUserList.value.forEach((item: ClientUserVo) => {
        item.statusMsg = UserStatusMap.get(item.status ?? "") ?? "未知";
      });
      loading.value = false;
      return true;
    }

    loading.value = false;
    return false;
  };

  // // 获取所有地区
  // const getDefaultTree = async () => {
  //   // 获取地区Tree
  //   const { data } = await getDefaultRegionTreeApi();
  //   searchData.searchRegionTree = data;
  //   // 获取组织
  //   const res = await getOrganizationApi(searchData.organizationParams);
  //   searchData.searchOrganizationTree = res.data;
  // };

  // // 获取区域id
  // const handleRegionChange = (selectedData: any) => {
  //   if (selectedData && selectedData.length > 0) {
  //     queryParams.value.regionId = selectedData[selectedData.length - 1];
  //   }
  // };

  // // 获取组织id
  // const handleOrganizationChange = (selectedData: any) => {
  //   if (selectedData && selectedData.length > 0) {
  //     queryParams.value.organizationId = selectedData[selectedData.length - 1];
  //   }
  // };

  /** 搜索按钮操作 */
  const handleQuery = () => {
    console.log(queryParams.value);
    queryParams.value.pageNum = 1;
    getClientUserList();
  };

  /**
   * 重置按钮操作
   */
  const resetQuery = () => {
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      phoneNumber: "",
      status: "",
      userName: "",
      time: "",
      regionId: "",
      organizationId: "",
      memberStatus: "",
    };
    handleQuery();
  };

  /**
   * 获取多选框选中数据
   */
  const handleSelectionChange = (selection: ClientUserVo[]) => {
    ids.value = selection.map((item) => item.id ?? "").filter((id) => id === "");
    // console.log('ID:!!!', ids.value[0])
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    // console.log(single.value, multiple.value)
  };

  /**
   * 处理新增按钮
   * */
  const handleCreate = async () => {
    dialog.visible = true;
    dialog.title = "新增客户端用户";
  };

  /**
   * 处理编辑按钮操作
   */
  const handleEditUser = async (row?: ClientUserVo) => {
    // loading.value = true;
    const id = row?.id ?? ids.value[0];
    dialog.title = "编辑客户端用户";
    const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
      getClientUserDetailApi(id),
    );

    if (!err) {
      dialogData.currentDialogData = res?.data?.user ?? initAddUserBO;
      // 获取详细信息之后再打开dialog
      dialog.visible = true;
    }
  };

  /**
   * 处理删除按钮操作
   */
  const handleDelete = async (row?: ClientUserVo) => {
    const _ids = row?.id || ids.value;
    const [err] = await to<BaseResponse<any>, any>(deleteClientUserApi(_ids));

    if (!err) {
      ElMessage({
        message: "删除客户端用户成功",
        type: "success",
      });
      await getClientUserList();
    }
  };

  /**
   * dialog中的关闭按钮
   */
  const handleCloseDialog = () => {
    currentDialogData.value = Object.assign({}, initAddUserBO);
    dialog.title = "";
    dialog.visible = false;
    loading.value = false;
    dialogData.isDisabled = false;
  };

  /**
   * 处理查看用户详情
   * @param row
   */
  const handleDetail = async (row: any) => {
    dialogData.isDisabled = true;
    dialog.title = "用户详情";
    const [err, res] = await to<BaseResponse<ClientUserInfoVo>, any>(
      getClientUserDetailApi(row.id),
    );
    if (!err) {
      dialogData.currentDialogData = res?.data?.user ?? initAddUserBO;
      dialog.visible = true;
    }
  };

  /**
   * 提交按钮
   */
  const addSubmit = () => {
    diologFormRef.value.validate(async (valid: boolean) => {
      console.log(currentDialogData.value);

      if (valid) {
        if (currentDialogData.value.id) {
          // 编辑修改用户
          await updateClientUserApi(currentDialogData.value);
          ElMessage({
            message: "用户修改成功",
            type: "success",
          });
          getClientUserList();
        } else {
          await createClientUserApi(currentDialogData.value);
          currentDialogData.value = Object.assign({}, initAddUserBO);
          ElMessage({
            message: "用户添加成功",
            type: "success",
          });
          getClientUserList();
        }
        dialog.visible = false;
        await getClientUserList();
      }
    });
  };

  // 获取导入模板
  // const getExportTemplate = async () => {
  //   const res = await getExportTemplateApi()
  //   console.log(res);
  // }

  /**
   * 导出按钮操作
   */
  const handleExport = () => {
    download(
      "/system/user/export",
      { ...queryParams.value },
      `demo_${new Date().getTime()}.xlsx`,
    );
  };

  // 上传到oss

  /**
   * 导入按钮
   */
  const handleImport = () => {};

  onMounted(() => {
    getClientUserList();
    // getDefaultTree();
  });
  </script>

  <style scoped lang="scss">
  .el-date-pickerv {
    width: 900px;
  }

  .dialogForm {
    padding: 0 0 0 45px;

    // background-color: pink;
    .el-input {
      width: 219px;
    }

    .el-select {
      width: 219px;
    }
  }

  .dialogFooter {
    margin: 40px 0 0 450px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    .setting {
      margin-left: 100px;
    }
  }
  </style>
